<template>
  <div class="body">
    <div class="container">
      <div class="title">
        <h1 v-text="files.fileName"></h1>
      </div>
       <div class="video-container"  >
        <video  id="my-video" class="video-js vjs-default-skin" controls preload="auto" width="100%" height="100%">
          <source src="" type="application/x-mpegURL">
          <p class="vjs-no-js">为了观看视频，请启用 JavaScript 并考虑升级到支持 HTML5 视频的浏览器。</p>
        </video>

      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted,ref,watch} from 'vue';
import Hls from 'hls.js';
import {useRoute} from "vue-router";
import {ElMessage} from "element-plus";
import {getFiles, show} from "../../api/system/files.js";
const hlsConfig={
  maxBufferLength: 60,
  maxBufferSize: 60 * 1024 * 1024,
  liveSyncDurationCount: 3
}

const files = ref({});
const  router = useRoute();
const id=router.query.id;


function getVideo(id){
  getFiles(id).then(response=>{
    files.value=response.data;
  })
}

function resetPlayer(video,hls){
  if(hls){
    hls.stopLoad();
  }
  video.currentTime = 0;
  video.pause();
}

function  tryPlay(video,hls,intervalId) {
  video.play().then(()=>{
    clearInterval(intervalId);
  }).catch(error=>{
    console.error('播放失败:', error);
    hls.destroy()
  })
}

function  reloadVideoSource(video,videoSrc,hlsConfig){
 console.log('加载视频源...')
  const hls = new Hls(hlsConfig);
  hls.loadSource(videoSrc);
  hls.attachMedia(video);
  return hls; // 返回 Hls 实例以便后续操作
}




onMounted(() => {
  getVideo(id);
  watch(files, (newFiles) => {
    if (newFiles && newFiles.fileUrl) {
      console.log('Files value:', newFiles); // 添加日志输出
      console.log("正在播放视频")
      const video = document.getElementById('my-video');
      const videoSrc = newFiles.m3u8Url; // 使用新获取的 fileUrl

      if (!videoSrc) {
        ElMessage.error('视频源为空，无法播放。');
        return;
      }

      if (Hls.isSupported()) {
        console.log('正在使用Hls.js播放视频...')
        const hls = new Hls(hlsConfig);
        hls.loadSource(videoSrc);
        hls.attachMedia(video);


        video.addEventListener('loadedmetadata', () => {
          console.log('视频元数据加载完成，正在尝试播放...')
          video.currentTime = 0;

          video.addEventListener('ended', () => {
            console.log('视频播放结束，正在重置播放器...')
            resetPlayer(video, hls);
          });
        });


        // 监听 Hls.js 的 error 事件
        hls.on(Hls.Events.ERROR, (event, data) => {

          if (data.type === Hls.ErrorTypes.NETWORK_ERROR) {
          if(data.details==='manifestLoadError'||data.details==='mediaLoadError') {
            hls.destroy();
            console.log('正在重新加载视频源...')
            show(newFiles.fileUrl, newFiles.rtmpUrl).then(response => {


              if (response.code === 200) {
                console.log('重新加载视频源成功')
                const intervalId = setInterval(() => {
                  const hls = reloadVideoSource(video, videoSrc, hlsConfig);
                  tryPlay(video, hls, intervalId);
                }, 3000); // 每3秒重试一次
              }
            });

          }
          if(data.fatal){
            hls.destroy()
          }


          } else if (data.details === 'bufferStalledError') {
            resetPlayer(video, hls);
          } else if (data.type === Hls.ErrorTypes.MEDIA_ERROR) {
            ElMessage.error('媒体错误。');
            console.error('媒体错误:', data.details, data.fatal);

            if (data.fatal) {
              hls.recoverMediaError();
            }
          } else {
            ElMessage.error('未知错误。');
            console.error('其他错误:', data.details, data.fatal);
          }
        });
      } else if (video.canPlayType('application/vnd.apple.mpegurl')) {
        const hls = new Hls(hlsConfig);
        video.src = videoSrc;
        video.currentTime = 0;
        video.addEventListener('ended', () => {
          resetPlayer(video, hls);
        });
      }
    }
  });
});

</script>

<style scoped>
.body {
  width: 100%;
  height: 100vh;
  margin: 0;
  padding: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #4d5154;
}

.container {
  height: 100vh;
  width: 80%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: rgba(255, 255, 255, 1);
}

.title {
  height: 10%;
  width: 100%;
}

.title h1 {
  font-size: 30px;
  text-align: left;
  margin-bottom: 20px;
}

.video-container {
  position: relative;
  width: 100%;
  height: 70%;
  overflow: hidden;
}

.video-js {
  width: 100%;
  height: 100%;
  object-fit: cover; /* 确保视频内容覆盖整个容器 */
}
</style>
